<template>
  <div class="app-container">
    <el-card class="operate-container" shadow="never">
      <el-form :inline="true" :model="listQuery" @submit.native.prevent ref="listQuery"  label-width="100px">
        <el-form-item label="角色名称:" prop="keyword" class="form-item">
          <el-input v-model="listQuery.name" class="filter-item" placeholder="角色名称"/>
        </el-form-item>
        <el-form-item class="form-item">
          <el-button type="primary" size="mini" icon="el-icon-search" @click="getList">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <div class="table_content">
      <div class="btn-btm">
        <el-button type="primary" plain size="mini" icon="el-icon-plus" @click="handleAdd">添加</el-button>
      </div>
      <!--表格渲染-->
      <el-table ref="table" v-loading="loading" :data="list" style="width: 100%;" border
                :header-cell-style="{background: '#F8F8F9',padding: '6px 0 !important',color: '#515a6e'}">
        <el-table-column prop="name" label="角色名称"/>
        <el-table-column prop="description" label="角色描述"/>
        <el-table-column prop="status" label="启用状态">
          <template slot-scope="scope">
            <span :style="{color: scope.row.status ==0 ?'#409EFF':'#CC3333'}">
            {{{'0':'启用','1':'停用'}[scope.row.status]}}
          </span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间"/>
        <el-table-column align="center" fixed="right" label="操作" min-width="120">
          <template slot-scope="scope">
            <el-button class="btn" type="text" size="small"
                       @click="handleEdit(scope.$index,scope.row,'update')">编辑</el-button>
            <el-popover
              placement="top"
              width="200"
              trigger="manual"
              :ref="'popover-' + scope.row.id">
              <p>确定删除该数据吗？</p>
              <div style="text-align: right; margin: 0">
                <el-button size="mini" type="text" @click="$refs[`popover-` + scope.row.id].doClose()">取消</el-button>
                <el-button type="primary" size="mini" @click="handleDel(scope.$index,scope.row)">确定</el-button>
              </div>
              <el-button class="btn" type="text" size="small" slot="reference"
                         @click="$refs[`popover-` + scope.row.id].doShow()">删除</el-button>
            </el-popover>
            <el-button class="btn" type="text" size="small"
                       v-if="scope.row.status == 0"
                       @click="roleEdit(scope.$index,scope.row,'update')">可使用功能</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页-->
      <pagination v-show="total>0" :total="total"
                  :page.sync="listQuery.pageNum"
                  :limit.sync="listQuery.pageSize"
                  @pagination="getList" />
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible"
               :close-on-click-modal="false" width="35%">
      <el-form :model="editForm" label-width="140px" :rules="editFormRules" ref="editForm">
        <el-form-item label="角色名称" prop="name" class="form-item">
          <el-input v-model="editForm.name" placeholder="角色名称" class="filter-item"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="description" class="form-item">
          <el-input v-model="editForm.description" placeholder="角色描述" class="filter-item"></el-input>
        </el-form-item>
        <el-form-item label="启用状态" prop="status" class="form-item">
          <el-switch
            v-model="editForm.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="0"
            :inactive-value="1">
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click.native="dialogFormVisible=false">取消</el-button>
        <el-button type="primary" size="mini" @click="createData">
          {{dialogStatus == 'create' ? '添加' : '保存'}}
        </el-button>
      </div>
    </el-dialog>

    <el-dialog title="选择可使用菜单功能" :visible.sync="dialogMenuVisible" :close-on-click-modal="false">
      <el-form :model="menuForm" label-width="120px" :rules="menuFormRules" ref="menuForm">
        <el-form-item label="选择菜单" prop="name" class="form-item">
         <!-- <el-tree
            :data="menuList"
            :props="menuProps"
            node-key="id"
            ref="tree"
            show-checkbox
            @check-change="handleCheckChange">
          </el-tree>-->
          <el-tree
            :data="menuList"
            show-checkbox
            default-expand-all
            node-key="id"
            ref="tree"
            highlight-current
            :check-strictly="checkStr"
            :props="menuProps">
          </el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click.native="dialogMenuVisible=false">取消</el-button>
        <el-button type="primary" size="mini" @click="createMenuData">提交</el-button>
      </div>
    </el-dialog>

    <amend-pwd v-if="fistFlag == 0"></amend-pwd>
  </div>
</template>

<script>
  import { doPost, doGet, doFile, jsonPost } from '@/api/index'
  import Pagination from '@/components/Pagination/index'
  import { mapGetters } from 'vuex'

  export default {
    name: "role.vue",
    components: {
      Pagination
    },
    computed: {
      ...mapGetters([
        'name',
        'fistFlag',
        'userForm'
      ])
    },
    data() {
      return {
        list: [],
        total: 0,
        loading: true,
        listQuery: {
          pageSize: 10,
          pageNum: 1,
          name: ''
        },
        dialogStatus: '',
        textMap:{
          update: '编辑',
          create: '新增'
        },
        dialogFormVisible: false,
        editForm: {
          status: '',
          name: '',
          description: ''
        },
        editFormRules: {
          name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
          status: [{ required: true, message: '启用状态不能为空', trigger: 'blur' }]
        },
        dialogMenuVisible: false,
        menuForm: {
          menuIds: '',
          roleId: ''
        },
        menuFormRules: {},
        menuProps: {
          label: 'name',
          children: 'children'
        },
        menuList:[],
        checkStr: false
      }
    },
    created() {
      this.getList()
    },
    methods: {
      getList() {
        this.loading = true
        doPost('role/page',this.listQuery).then(res => {
          this.list = res.data.list
          this.loading = false
          this.total = res.data.total
        }).catch(error => {
          this.loading = false
          this.list = []
          this.total = 0
        })
      },
      handleAdd() {
        this.dialogFormVisible = true
        this.dialogStatus = 'create'
        this.editForm = {
          status: 0,
          name: '',
          description: ''
        }
      },
      //  分配菜单弹窗
      roleEdit(index,row) {
        this.dialogMenuVisible = true
        this.menuForm.roleId = row.id
        doPost('menu/treeList', {type:0}).then(res => {
          this.menuList = res.data
          this.menuGetList()
        }).catch(error => {
          this.menuList = []
        })
      },
      menuGetList() {
        this.checkStr = true
        doPost('role/menu/'+this.menuForm.roleId).then(res => {
          // this.menuList = res.data
          let menuList = res.data;
          let checkedMenuIds=[];
          if(menuList != null && menuList.length > 0){
            for(let i=0;i<menuList.length;i++){
              let menu = menuList[i];
              console.log('menu',menu)
              if(menu.parentId !== 0 || menu.parentId !== null){
                checkedMenuIds.push(menu.id);
              }
            }
          }
          this.$nextTick(() => {
            var checkedId = checkedMenuIds
            this.$refs.tree.setCheckedKeys(checkedId)    // 设置回显
            this.checkStr = false    // 回显完成后，再次设置互相关联
          })
          console.log('checkedMenuIds',checkedMenuIds)
          // this.$refs.tree.setCheckedKeys(checkedMenuIds);
        }).catch(error => {
          // this.menuList = []
        })
      },
      // 提交分配菜单
      createMenuData() {
        let checkedNodes = this.$refs.tree.getCheckedNodes();
        let checkedMenuIds=new Set();
        if(checkedNodes!=null&&checkedNodes.length>0){
          for(let i=0;i<checkedNodes.length;i++){
            let checkedNode = checkedNodes[i];
            checkedMenuIds.add(checkedNode.id);
            if(checkedNode.parentId!==0){
              checkedMenuIds.add(checkedNode.parentId);
            }
          }
        }
        let arr = Array.from(checkedMenuIds)
        console.log('checkedMenuIds',arr.join(','))
        let form = {
          roleId: this.menuForm.roleId,
          menuIds: arr.join(',')
        }
        doPost('role/allocMenu',form).then(res => {
          if (res.code == 200) {
            this.dialogMenuVisible = false
            this.getList()
            this.$message.success({
              type: 'success',
              message: '提交成功'
            })
          }
        }).catch(error => {
          this.$message.error(error.message)
        })
      },
      handleCheckChange(data, checked, indeterminate) {
        console.log(data, checked, indeterminate);
      },
      handleEdit(index, row) {
        this.dialogFormVisible = true
        this.dialogStatus = 'update'
        this.editForm = Object.assign({},row)
      },
      createData() {
        this.$refs['editForm'].validate(valid => {
          if (valid) {
            doPost(`role/${this.dialogStatus == 'create' ? 'add':'update'}`,this.editForm).then(res => {
              if (res.code == 200) {
                this.getList()
                this.dialogFormVisible = false
                this.$message.success({
                  type: 'success',
                  message: this.dialogStatus == 'create' ? '添加成功':'修改成功'
                })
              }
            }).catch(error => {
              this.$message.error(error.message)
            })
          }
        })
      },
      handleDel(index, row) {
        doPost('role/delete/'+row.id).then(res => {
            if (res.code == 200) {
              this.$message.success({
                type: 'success',
                message: '删除成功'
              })
              this.list.splice(index, 1)
              this.total--
              this.$refs[`popover-` + row.id].doClose()
            } else {
              this.$refs[`popover-` + row.id].doClose()
              this.$message.error(res.message)
            }
          }).catch(error => {
          this.$refs[`popover-` + row.id].doClose()
          this.$message.error(error.message)
        })
      },
    }
  }
</script>

<style lang="scss" scoped>

</style>
